# app/serializers.py
from rest_framework import serializers
from .models import ScheduledTask, TaskExecutionLog, TaskMetrics


class ScheduledTaskSerializer(serializers.ModelSerializer):
    """调度任务序列化器"""
    
    class Meta:
        model = ScheduledTask
        fields = '__all__'
        read_only_fields = ('job_id', 'last_run_time', 'next_run_time', 'created_at', 'updated_at')
    
    def validate_trigger_config(self, value):
        """验证触发器配置"""
        if not isinstance(value, dict):
            raise serializers.ValidationError("触发器配置必须是字典格式")
        return value
    
    def validate(self, data):
        """验证整体数据"""
        trigger_type = data.get('trigger_type')
        trigger_config = data.get('trigger_config', {})
        
        # 根据触发器类型验证配置
        if trigger_type == 'interval':
            required_fields = ['seconds', 'minutes', 'hours', 'days']
            if not any(field in trigger_config for field in required_fields):
                raise serializers.ValidationError(
                    "间隔触发器至少需要指定 seconds, minutes, hours, days 中的一个"
                )
        elif trigger_type == 'cron':
            # Cron 触发器可以接受多种格式，这里做基础验证
            pass
        elif trigger_type == 'date':
            if 'run_date' not in trigger_config:
                raise serializers.ValidationError(
                    "日期触发器必须指定 run_date"
                )
        
        return data


class ScheduledTaskCreateSerializer(ScheduledTaskSerializer):
    """创建调度任务的序列化器"""
    
    def create(self, validated_data):
        """创建任务时自动生成 job_id"""
        import uuid
        from django.utils import timezone
        
        if 'job_id' not in validated_data:
            validated_data['job_id'] = f"task_{uuid.uuid4().hex[:8]}_{int(timezone.now().timestamp())}"
        
        return super().create(validated_data)


class TaskExecutionLogSerializer(serializers.ModelSerializer):
    """任务执行日志序列化器"""
    
    scheduled_task_name = serializers.CharField(source='scheduled_task.name', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    
    class Meta:
        model = TaskExecutionLog
        fields = '__all__'
        read_only_fields = ('start_time', 'end_time', 'execution_time')


class TaskMetricsSerializer(serializers.ModelSerializer):
    """任务统计序列化器"""
    
    scheduled_task_name = serializers.CharField(source='scheduled_task.name', read_only=True)
    success_rate = serializers.FloatField(read_only=True)
    
    class Meta:
        model = TaskMetrics
        fields = '__all__'
        read_only_fields = '__all__'


class TaskTriggerConfigSerializer(serializers.Serializer):
    """触发器配置辅助序列化器"""
    
    # 间隔触发器
    seconds = serializers.IntegerField(required=False, min_value=0)
    minutes = serializers.IntegerField(required=False, min_value=0)
    hours = serializers.IntegerField(required=False, min_value=0)
    days = serializers.IntegerField(required=False, min_value=0)
    
    # Cron 触发器
    second = serializers.CharField(required=False)
    minute = serializers.CharField(required=False)
    hour = serializers.CharField(required=False)
    day = serializers.CharField(required=False)
    month = serializers.CharField(required=False)
    day_of_week = serializers.CharField(required=False)
    week = serializers.CharField(required=False)
    year = serializers.CharField(required=False)
    
    # 日期触发器
    run_date = serializers.DateTimeField(required=False)


class AsyncTaskSubmitSerializer(serializers.Serializer):
    """异步任务提交序列化器"""
    
    strategy_id = serializers.CharField(max_length=255)
    module_path = serializers.CharField(max_length=500)
    function_name = serializers.CharField(max_length=255)
    args = serializers.ListField(default=list, required=False)
    kwargs = serializers.DictField(default=dict, required=False)


class TaskControlSerializer(serializers.Serializer):
    """任务控制序列化器"""
    
    action = serializers.ChoiceField(
        choices=[
            ('pause', '暂停'),
            ('resume', '恢复'), 
            ('run_now', '立即运行'),
            ('delete', '删除')
        ]
    )


class SchedulerStatusSerializer(serializers.Serializer):
    """调度器状态序列化器"""
    
    running = serializers.BooleanField(read_only=True)
    job_count = serializers.IntegerField(read_only=True)
    next_run_time = serializers.DateTimeField(read_only=True, allow_null=True)


class JobInfoSerializer(serializers.Serializer):
    """任务信息序列化器"""
    
    id = serializers.CharField(read_only=True)
    name = serializers.CharField(read_only=True)
    next_run_time = serializers.DateTimeField(read_only=True, allow_null=True)
    trigger = serializers.CharField(read_only=True)
    pending = serializers.BooleanField(read_only=True)